// Triangulation.cpp
//
#include "Triangulation.h"

extern "C" {
#include "triangle.h"
}

using namespace glm;

std::vector<unsigned int> Triangulation::triangulate3D( const std::vector<Math::dvec3> &vtx )
{
	triangulateio in, out;
	memset(&in, 0, sizeof(in));
	memset(&out, 0, sizeof(out));

	// Fill in input structure
	in.numberofpoints = vtx.size();
	in.pointlist = new REAL[2*in.numberofpoints];
	for( int j=0; j<in.numberofpoints; ++j )
	{
		in.pointlist[2*j+0] = vtx[j][0];
		in.pointlist[2*j+1] = vtx[j][1];
	}
	
	//triangulate("cpNBPIzQ", &in, &out, 0);
	triangulate("cpNBPIzQ", &in, &out, 0);

	delete[] in.pointlist;

	std::vector<unsigned int> v;
	if (out.numberofcorners != 3 || out.numberofpoints != in.numberofpoints)
		return v;

	for( int i=0; i<out.numberoftriangles; ++i )
	{
		v.push_back( out.trianglelist[3*i+0] );
		v.push_back( out.trianglelist[3*i+1] );
		v.push_back( out.trianglelist[3*i+2] );
	}

	trifree(out.trianglelist);

    return v;
}